package com.vhall.component.plugin.common.utils;

import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * http://cwe.mitre.org/data/definitions/23.html
 *
 * @author yongzheng.xu
 * @date 2021/6/7 19:38
 */
@Slf4j
public class DirUtil {

    public static void failIfDirectoryTraversal(String relativePath) {

        File file = new File(relativePath);
        log.error("路径判断1:{}", relativePath);
        if (file.isAbsolute()) {
            throw new BusinessException(BizErrorCode.EMPTY_DIR_ERROR);
        }

        String pathUsingCanonical;
        String pathUsingAbsolute;
        try {
            pathUsingCanonical = file.getCanonicalPath();
            pathUsingAbsolute = file.getAbsolutePath();
        } catch (Exception e) {
            throw new BusinessException(BizErrorCode.EMPTY_DIR_ERROR);
        }

        log.error("路径判断2:{}", pathUsingCanonical);
        log.error("路径判断3:{}", pathUsingAbsolute);
        // Require the absolute path and canonicalized path match.
        // This is done to avoid directory traversal
        // attacks, e.g. "1/../2/"
        if (!pathUsingCanonical.equals(pathUsingAbsolute)) {
            //throw new RuntimeException("Directory traversal attempt?");
            throw new BusinessException(BizErrorCode.EMPTY_DIR_ERROR);
        }
    }
}
